package com.foot.travel.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

import org.hybridsquad.android.library.CropHelper;
import org.hybridsquad.android.library.CropParams;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.GalleryFinal.OnHanlderResultCallback;
import cn.finalteam.galleryfinal.model.PhotoInfo;

import com.foot.travel.R;
import com.foot.travel.adapter.UpLoadImageAdapter;
import com.koalac.ironman.cache.SysAppConfig;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.ResponseProcess;
import com.koalac.ironman.net.pojo.request.UpdateMyDetail;
import com.koalac.ironman.net.pojo.request.UploadImage;
import com.koalac.ironman.net.pojo.response.Picture;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.net.pojo.response.User;
import com.koalac.ironman.util.BitmapUtil;
import com.koalac.ironman.util.ScreenInfoUtil;
import com.koalac.ironman.util.StringUtils;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.ActionSheet;
import com.koalac.ironman.widget.ActionSheet.ActionSheetListener;
import com.koalac.ironman.widget.ActionSheet.Builder;
import com.koalac.ironman.widget.ImageLoadAgreement.ImageType;
import com.koalac.ironman.widget.LifeqImageView;
import com.koalac.ironman.widget.LoadingDialog;

public class UpdateMyActivity extends ModuleActivity implements
	OnClickListener, OnHanlderResultCallback {

    @ViewInject(id = R.id.select_head_photo, click = "onClick")
    ImageView mSelectHeadPhotoBtn;
    @ViewInject(id = R.id.woman_select, click = "onClick")
    ImageView mWomanSelectView;
    @ViewInject(id = R.id.man_select, click = "onClick")
    ImageView mManSelectView;
    @ViewInject(id = R.id.school_name)
    EditText mSchoolNameView;
    @ViewInject(id = R.id.class_name)
    EditText mClassNameView;
    @ViewInject(id = R.id.where)
    EditText mWhereView;
    @ViewInject(id = R.id.introduce)
    EditText mIntroduceView;
    @ViewInject(id = R.id.hobby)
    EditText mHobbyView;
    @ViewInject(id = R.id.account_name)
    EditText mAccountView;
    @ViewInject(id = R.id.cover)
    LifeqImageView mCoverView;
    @ViewInject(id = R.id.nickname)
    TextView mNicknameView;
    @ViewInject(id = R.id.parent_view)
    View mParentView;
    @ViewInject(id = R.id.cover_layout)
    View mCoverLayout;

    private String mHeadPhotoUrl;
    private String mSex;

    User mUser;
    public static final String USER_DATA = "user_data";

    Builder mBuilder;
    public static final int SELECT_CAMERA = 0;
    public static final int SELECT_PHOTO = 1;
    CropParams mCropParams = new CropParams();
    private String mHeadPhotoFilePath;
    private String mHeadPhotoFileName;
    public static final int REQUEST_CODE = 1;
    public static final int REQUEST_CROP = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setNavigationTitle("修改个人资料");
	setBackButtonVisibility(true);
	setTheme(R.style.ActionSheetStyleIOS7);
	seSaveButtonVisibility(true);
	mSaveView.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		if (checkInput()) {
		    if (StringUtils.isEmpty(mHeadPhotoFilePath)) {
			uploadMyDetail();
		    } else {
			uploadHeadPhoto();
		    }
		}
	    }
	});
	setCoverViewHeight();
	init();
	checkKeyboardHeight(mParentView, 0);
    }
    private void setCoverViewHeight() {
	int height = ScreenInfoUtil.getScreenWidth(UpdateMyActivity.this);
	RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) mCoverView
			.getLayoutParams();
	layoutParams.height = height;
	mCoverView.setLayoutParams(layoutParams);
	RelativeLayout.LayoutParams layoutParams1 = (android.widget.RelativeLayout.LayoutParams) mCoverView
		.getLayoutParams();
layoutParams1.height = height;
	mCoverLayout.setLayoutParams(layoutParams1);
}

    private void init() {
	mUser = (User) getIntent().getSerializableExtra(USER_DATA);

	mSex = mUser.getSex();
	mManSelectView.setSelected(mSex.equals(User.SEX_MALE));
	mWomanSelectView.setSelected(mSex.equals(User.SEX_FEMALE));

	mSchoolNameView.setText(mUser.getSchool());
	mClassNameView.setText(mUser.getClasses());
	mWhereView.setText(mUser.getRegion());

	mIntroduceView.setText(mUser.getMessage());
	mHobbyView.setText(mUser.getHobby());
	mNicknameView.setText(mUser.getUser_name());
	mAccountView.setText(mUser.getAccount());

	mCoverView.loadFile(mUser.getHead_img_url(), ImageType.SourceImage,
		null, null);
	mHeadPhotoUrl = mUser.getHead_img_url();

	mBuilder = ActionSheet
		.createBuilder(getApplicationContext(),
			getSupportFragmentManager())
		.setListener(new ActionSheetListener() {

		    @Override
		    public void onOtherButtonClick(ActionSheet actionSheet,
			    int index) {
			FunctionConfig config;
			switch (index) {
			case SELECT_CAMERA:
			    config = new FunctionConfig.Builder()
				    .setMutiSelectMaxSize(1).setEnableCrop(true).setCropSquare(true).build();
			    GalleryFinal.openCamera(REQUEST_CODE, config,
				    UpdateMyActivity.this);
			    break;
			case SELECT_PHOTO:
			    config = new FunctionConfig.Builder()
				    .setMutiSelectMaxSize(1).setEnableCrop(true).setCropSquare(true).setForceCrop(true).build();
			    GalleryFinal.openGalleryMuti(REQUEST_CODE, config,
				    UpdateMyActivity.this);
			    break;
			}
		    }

		    @Override
		    public void onDismiss(ActionSheet actionSheet,
			    boolean isCancel) {

		    }
		}).setOtherButtonTitles(new String[] { "拍照", "相册" })
		.setCancelButtonTitle("取消");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void initLayout(ViewGroup rootContentView) {
	addContentView(R.layout.activity_update_my);
    }

    private boolean checkInput() {
	if (StringUtils.isEmpty(mHeadPhotoUrl)
		&& StringUtils.isEmpty(mHeadPhotoFilePath)) {
	    toast("头像不能为空!");
	    return false;
	}
	if (StringUtils.isEmpty(mAccountView.getText().toString())) {
	    toast("账户不能为空!");
	    return false;
	}
	if (StringUtils.isEmpty(mNicknameView.getText().toString())) {
	    toast("昵称不能为空!");
	    return false;
	}
	if (StringUtils.isEmpty(mSex)) {
	    toast("你还没选择性别!");
	    return false;
	}

	if (StringUtils.isEmpty(mSchoolNameView.getText().toString())) {
	    toast("学校单位不能为空!");
	    return false;
	}
	if (StringUtils.isEmpty(mClassNameView.getText().toString())) {
	    toast("班级/部门不能为空!");
	    return false;
	}
	if (StringUtils.isEmpty(mWhereView.getText().toString())) {
	    toast("来自选项不能为空!");
	    return false;
	}
//	if (StringUtils.isEmpty(mIntroduceView.getText().toString())) {
//	    toast("个人简介不能为空!");
//	    return false;
//	}
//	if (StringUtils.isEmpty(mHobbyView.getText().toString())) {
//	    toast("兴趣爱好不能为空!");
//	    return false;
//	}
	return true;
    }

    @Override
    public void onClick(View v) {
	int viewId = v.getId();
	switch (viewId) {
	case R.id.select_head_photo:
	    mBuilder.show();
	    break;
	case R.id.woman_select:
	    mSex = "female";
	    mManSelectView.setSelected(false);
	    mWomanSelectView.setSelected(true);
	    break;
	case R.id.man_select:
	    mSex = "male";
	    mManSelectView.setSelected(true);
	    mWomanSelectView.setSelected(false);
	    break;
	default:
	    break;
	}
    }

    private void uploadMyDetail() {
	final LoadingDialog loadingDialog = showLoadingDialog("更新个人资料...");
	UpdateMyDetail mUpdateMyDetail = new UpdateMyDetail();

	mUpdateMyDetail.setUser_name(mUser.getUser_name());
	mUpdateMyDetail.setHead_img_url(mHeadPhotoUrl);
	mUpdateMyDetail.setSex(mSex);

	mUpdateMyDetail.setAccount(mAccountView.getText().toString());
	mUpdateMyDetail.setSchool(mSchoolNameView.getText().toString());
	mUpdateMyDetail.setClasses(mClassNameView.getText().toString());

	mUpdateMyDetail.setRegion(mWhereView.getText().toString());
	mUpdateMyDetail.setMessage(mIntroduceView.getText().toString());
	mUpdateMyDetail.setHobby(mHobbyView.getText().toString());

	MyRequest.request(getApplicationContext(), mUpdateMyDetail,
		new ResponseCallback() {

		    @Override
		    public void process(boolean result, Context context,
			    Response data, String msg) {
			canceledLoadingDialog(loadingDialog);
			if (result) {
			    User user = data.getObject(User.class);
			    user.setUser_name(mUser.getUser_name());
			    SysAppConfig.getInstance().setUser(context, user);
			    Intent intent = new Intent();
			    intent.putExtra(USER_DATA, user);
			    setResult(RESULT_OK, intent);
			    UpdateMyActivity.this.finish();

			}
		    }
		});
    }

    private void uploadHeadPhoto() {
	final LoadingDialog loadingDialog = showLoadingDialog("上传头像...");
	UploadImage uploadImage = new UploadImage();
	ByteArrayOutputStream outputStream = BitmapUtil.compressByCale2Stream(
		mHeadPhotoFilePath, 480, 800, 200);
	MyRequest.upload(outputStream, mHeadPhotoFileName,
		getApplicationContext(), uploadImage, new ResponseProcess() {

		    @Override
		    public void onProcess(Context context, float process) {

		    }
		}, new ResponseCallback() {

		    @Override
		    public void process(boolean result, Context context,
			    Response data, String msg) {
			canceledLoadingDialog(loadingDialog);
			if (result) {
			    Picture picture = data.getObject(Picture.class);
			    mHeadPhotoUrl = picture.getUpyunPath();
			    uploadMyDetail();
			}
		    }
		});
    }

    @Override
    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
	mHeadPhotoFilePath = resultList.get(0).getPhotoPath();
	mCoverView.displayLocalFile(mHeadPhotoFilePath, ImageType.SourceImage,
		null);
	FunctionConfig config = new FunctionConfig.Builder()
	    .setMutiSelectMaxSize(1).setEnableCrop(true).setCropSquare(true).build();
	if (reqeustCode == REQUEST_CODE) {
	    GalleryFinal.openCrop(REQUEST_CROP,config,mHeadPhotoFilePath,UpdateMyActivity.this);
	}
    }

    @Override
    public void onHanlderFailure(int requestCode, String errorMsg) {

    }

}
